import { createRouter, createWebHistory } from 'vue-router'

// 导入页面组件
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
const Home = () => import('../views/Home.vue')
const ActivityList = () => import('../views/ActivityList.vue')
const ActivityDetail = () => import('../views/ActivityDetail.vue')
const ActivityEdit = () => import('../views/ActivityEdit.vue')
const UserProfile = () => import('../views/UserProfile.vue')
const MyActivities = () => import('../views/MyActivities.vue')
const NotFound = () => import('../views/NotFound.vue')

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: false }
  },
  {
    path: '/activities',
    name: 'ActivityList',
    component: ActivityList,
    meta: { requiresAuth: false }
  },
  {
    path: '/activity/:id',
    name: 'ActivityDetail',
    component: ActivityDetail,
    meta: { requiresAuth: false }
  },
  {
    path: '/activity-edit',
    name: 'ActivityEdit',
    component: ActivityEdit,
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-edit/:id',
    name: 'ActivityUpdate',
    component: ActivityEdit,
    meta: { requiresAuth: true }
  },
  {
    path: '/profile',
    name: 'UserProfile',
    component: UserProfile,
    meta: { requiresAuth: true }
  },
  {
    path: '/my-activities',
    name: 'MyActivities',
    component: MyActivities,
    meta: { requiresAuth: true }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      // 未登录，重定向到登录页
      return next('/login')
    }
    // 判断是否需要管理员权限
    if (to.meta.requiresAdmin) {
      // 这里简化处理，实际应该根据用户角色判断
      // const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      // if (!userInfo.roles || !userInfo.roles.includes('ADMIN')) {
      //   return next('/home')
      // }
    }
  }
  next()
})

export default router